<template>
	<view class="nas-transfer">
		<u-subsection :list="list" :current="current" active-color="#fff" bg-color="#F5F5F5" button-color="#3069DC" font-size="28" bold></u-subsection>
		<view class="nas-transfer-status">
			<view class="nas-transfer-status-left">
				<view class="nas-transfer-left-item">正在上传({{ taskFileList.length }})</view>
				<view class="nas-transfer-left-item">
					<image src="../../../static/nas-static/nas-lingt.svg" mode=""></image>
					<view>您正在享受极速传输服务</view>
				</view>
			</view>
			<view class="nas-transfer-status-right">全部暂停</view>
		</view>
		<!-- <view @click="dealUploading">{{ test }}</view> -->
		<!-- 列表部分 -->
		<view class="nas-transfer-body" v-for="(item, index) in taskFileList" :key="index">
			<view class="nas-transfer-body-item">
				<view class="nas-transfer-body-left"><image src="../../../static/nas-static/nas-list-file.svg" mode=""></image></view>
				<view class="nas-transfer-body-info">
					<view class="nas-transfer-info">{{ item.name }}</view>
					<view class="nas-transfer-info"><progress :percent="getProgress(item)" :show-info="false" stroke-width="3" /></view>
					<view class="nas-transfer-info">
						<view>{{ dealSize(item.size) }}</view>
						<!-- <view>2.8MB/s</view> -->
						<view>{{ item.totalPieces }}</view>
					</view>
				</view>
				<view class="nas-transfer-body-right" @click="pause(item)">
					<image v-if="!item.pause" src="../../../static/nas-static/nas-gonow.svg" mode=""></image>
					<image v-if="item.pause" src="../../../static/nas-static/nas-goupload.svg" mode=""></image>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import request from '../utils/request.js';
export default {
	data() {
		return {
			list: [
				{
					name: '上传中'
				},
				{
					name: '上传完成'
				},
				{
					name: '下载中'
				},
				{
					name: '下载完成'
				}
			],
			current: 0, // 当前的tab
			taskFileList: [], // 上传任务队列
			test: 0
		};
	},
	onLoad(e) {
		// 保存的文件目录
		const filePath = e.filePath || '';
		// if (this.taskFileList.length === 0) {
		// 	console.log('我进来了');
		this.dealUploading(filePath);
		// }
	},
	onUnload() {
		console.log('页面卸载了');
		// 全部暂停
		// this.taskFileList.forEach(val => (val.pause = true));
	},
	methods: {
		// 统一处理上传的任务
		dealUploading(filePath) {
			/**
			 * 切片任务命名规则nas_id_随机字符（暂定10位）
			 */
			const storageKeys = this.getKeys();
			// 1、查看是否有未完成的切片上传任务，有则断点续传
			// 从缓存中取出上传的任务id队列
			const taskIdList = storageKeys.filter(val => val.indexOf('nas_id_') !== -1);
			console.log(taskIdList, 'taskIdList');
			if (taskIdList.length > 0) {
				// 从缓存中取出id对应的内容
				// taskIdList.forEach(pr => {
				// 	const info = JSON.parse(uni.getStorageSync(pr));
				// 	this.taskFileList.push(info);
				// 	// uni.removeStorageSync(pr);
				// });
				for (let i = 0; i < taskIdList.length; i++) {
					// uni.removeStorageSync(taskIdList[i]);
					const info = JSON.parse(uni.getStorageSync(taskIdList[i]));
					this.taskFileList.push(info);
				}
				// 进行切片上传
				this.taskFileList.forEach((pd, index) => {
					this.apiUploadFiles(pd.sliceKey);
				});
			}
			// 2、检查是否有未切片的文件，有则先进行切片再上传
			// 从缓存中取出未切片的队列
			const tempList = storageKeys.filter(val => val.indexOf('nas_temp_') !== -1);
			if (tempList.length > 0) {
				tempList.forEach(ped => {
					const info = JSON.parse(uni.getStorageSync(ped));
					console.log(info, 'info');
					// 对文件进行切片
					const { path, name, tempKey, size } = info;
					this.sliceFiles(path, name, tempKey, size, filePath);
				});
			}
		},
		/**
		 * @param {Object} path 临时文件的路径
		 * @param {Object} name 文件的名称
		 * @param {Object} tempKey 缓存中的key
		 * @param {Object} size 文件的大小
		 */
		sliceFiles(path, name, tempKey, size, filePath) {
			// 大于4M的文件才需要进行切片
			if (size > 1024 * 1024) {
				if (path.indexOf('_doc') != -1) {
					path = plus.io.convertLocalFileSystemURL(path); // 将本地URL路径转换成平台绝对路径
				} else {
					path = path.replace('file://', '');
				}
				// 调用分片插件
				const KJFileSlice = uni.requireNativePlugin('KJ-FileSlice');
				var dic = {
					pathFileName: path,
					savePath: plus.io.convertLocalFileSystemURL('_doc/KJ-FileSlice'), //保存切片地址，一定要是_doc目录
					sliceSize: 1024 * 1024, // 每个文件切片大小定为4MB
					sliceSuffixName: '' //保存切片的后缀名
				};
				KJFileSlice.start(dic, res => {
					// 切片完成删除缓存里面的key
					uni.removeStorageSync(tempKey);
					// 切片后的文件保存到缓存中
					const sliceKey = 'nas_id_' + this.uuid(10, 10);
					const saveInfo = {
						sliceKey: sliceKey, // 同缓存的key
						name: name, // 切片对应的文件名称
						percent: 0, // 进度（默认从第一个切片开始上传）
						totalPieces: res.slices.length, // 总切片数
						pause: false, // 是否暂停该任务
						size: size, // 文件的大小
						content: res.slices, // 切片的内容数组
						filePath: filePath, // 文件上传的目录
						isError: false // 上传失败了么
					};
					uni.setStorageSync(sliceKey, JSON.stringify(saveInfo));
					this.taskFileList.push(saveInfo);
					// console.log(this.taskFileList, 'this.taskFileList');
					this.apiUploadFiles(sliceKey);
				});
			} else {
				const sliceKey = 'nas_id_' + this.uuid(10, 10);
				const saveInfo = {
					sliceKey: sliceKey, // 同缓存的key
					name: name, // 切片对应的文件名称
					percent: 0, // 进度（默认从第一个切片开始上传）
					totalPieces: 1, // 总切片数
					pause: false, // 是否暂停该任务
					size: size, // 文件的大小
					content: {
						filePath: path
					}, // 切片的内容数组
					filePath: filePath, // 文件上传的目录
					isError: false // 上传失败了么
				};
				uni.setStorageSync(sliceKey, JSON.stringify(saveInfo));
				this.taskFileList.push(saveInfo);
				// console.log(this.taskFileList, 'this.taskFileList');
				this.apiUploadFiles(sliceKey);
			}
		},
		// 文件上传
		async apiUploadFiles(sliceKey) {
			const index = this.taskFileList.findIndex(pre => pre.sliceKey === sliceKey);
			const taskObj = this.taskFileList[index];
			// 先获取token再进行切片上传
			const params = {
				method: 'POST',
				url: '/nas/user/upload/userInfo',
				contentType: 'application/x-www-form-urlencoded',
				data: {
					pathFileName: taskObj.filePath + taskObj.name,
					uploadType: 0
				}
			};
			// console.log(params, '获取token的请求头')
			const resInfo = await request(params);
			const token = resInfo.data;
			if (taskObj.percent === taskObj.content.length - 1) return;
			for (let i = taskObj.percent; i < taskObj.content.length; i++) {
				// 暂停下载
				if (taskObj.pause) return;
				const content = taskObj.content[i];
				const formData = {
					fileName: taskObj.name + '.crash',
					offset: 1024 * 1024 * i,
					directory: taskObj.filePath
				};
				const res = await this.addFile(content, formData, token);
				// 更新缓存中的数据
				uni.setStorageSync(sliceKey, JSON.stringify(taskObj));
				if (res) {
					// 更新缓存里的数据
					taskObj.percent = i + 1;
					// this.test = taskObj.percent;
					// 文件全部上传完成
					if (taskObj.percent === taskObj.content.length) {
						// 判断文件是否上传成功，不存在则上传失败重新进行上传任务
						this.isSuccess(taskObj);
						this.clearInfos(sliceKey);
					}
					// 更新页面的数据
					this.$forceUpdate();
					// 上传成功
				} else {
					taskObj.isError = true;
					return false;
				}
			}
		},
		// 判断是否存在这个文件，如果存在则修改名字
		async isSuccess(taskObj) {
			const params = {
				method: 'POST',
				url: '/nas/rd_center/data/get',
				data: {
					method: 'capacity.nas.cloud.file.exist',
					type: 1,
					data: {
						directory: taskObj.filePath,
						filename: taskObj.name + '.crash'
					}
				}
			};
			// console.log(params, '判断是否存在的请求头');
			const res = await request(params);
			// console.log(res, '判断是否存在的返回结果');
			if (res.data) {
				// 改变文件的名称
				const requestInfo = {
					method: 'POST',
					url: '/nas/rd_center/data/get',
					data: {
						method: 'capacity.nas.cloud.file.rename',
						type: 1,
						data: {
							directory: taskObj.filePath,
							filename: taskObj.name + '.crash',
							newFilename: taskObj.name
						}
					}
				};
				// console.log(requestInfo, '重命名的请求头');
				request(requestInfo);
			} else {
				taskObj.isError = true;
			}
			// console.log(res, '查询文件是否存在')
		},
		// 清除缓存的任务
		clearInfos(sliceKey) {
			this.taskFileList.splice(this.taskFileList.findIndex(pre => pre.sliceKey === sliceKey), 1);
			uni.removeStorageSync(sliceKey);
			// 全部上传完成，清除切片所有数据
			const taskIdList = storageKeys.filter(val => val.indexOf('nas_id_') !== -1);
			let allTask = [];
			taskIdList.forEach(pr => {
				const info = JSON.parse(uni.getStorageSync(pr));
				allTask.push(info);
			});
			const goNeed = allTask.some(val => val.percent !== val.totalPieces);
			if (!goNeed) {
				this.deleteSliceData();
			}
		},
		// 清除所有的切片
		deleteSliceData() {
			let dirPath = '_doc/KJ-FileSlice';
			plus.io.resolveLocalFileSystemURL(
				dirPath,
				function(entry) {
					//读取这个目录对象
					var directoryReader = entry.createReader();
					//读取这个目录下的所有文件
					directoryReader.readEntries(
						function(entries) {
							console.log(entries.length);
							//如果有才操作
							if (entries.length > 0) {
								//删除目录将会删除其下的所有文件及子目录 不能删除根目录，如果操作删除根目录
								//将会删除目录下的文件及子目录，不会删除根目录自身。 删除目录成功通过succesCB
								//回调返回，失败则通过errorCB返回。
								entry.removeRecursively(
									function(entry) {
										console.log('删除成功回调');
									},
									function(e) {
										console.log(e.message + ' ?!');
									}
								);
							}
						},
						function(e) {
							console.log('读取文件失败：' + e.message);
						}
					);
				},
				function(e) {
					console.log('读取目录失败：' + e.message);
				}
			);
		},
		/**
		 * @param {Object} content 上传组件需要的参数
		 * @param {Object} formData 需要传给后台的参数
		 * @param {Object} token 需要传给后台的token
		 */
		addFile(content, formData, token) {
			// console.log('开始上传content', content);
			// console.log('开始上传formData', formData);
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: 'http://58.34.36.138:18480/nasforward/file/upload?uploadToken=' + token,
					filePath: content.filePath,
					formData: formData,
					name: 'content',
					// header: {
					// 	'Content-Type': 'multipart/form-data'
					// },
					success: res => {
						resolve(res);
						console.log(res, '上传返回的参数');
					},
					fail: err => {
						console.log(err, '上传失败');
					}
				});
			});
		},
		// 获取缓存中的key值
		getKeys() {
			let keys = [];
			uni.getStorageInfo({
				success(res) {
					keys = res.keys;
				}
			});
			return keys;
		},
		// 暂停下载
		pause(item) {
			item.pause = !item.pause;
			if (!item.pause) {
				// 重新开启下载
				this.apiUploadFiles(item.sliceKey);
			}
		},
		// 计算进度
		getProgress(item) {
			return Math.floor((item.percent / item.totalPieces) * 100);
		},
		// 计算文件的大小
		dealSize(item) {
			if (item > 1024 * 1024) {
				return parseFloat(item / (1024 * 1024)).toFixed(2) + 'MB';
			} else {
				return parseFloat(item / (1024 * 1024)).toFixed(2) + 'KB';
			}
		},
		// 生成随机数，指定长度和基数
		uuid(len, radix) {
			let chars = 'GHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
			let uuid = [],
				i;
			radix = radix || chars.length;
			if (len) {
				for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
			} else {
				let r = null;
				uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
				uuid[14] = '4';
				for (i = 0; i < 36; i++) {
					if (!uuid[i]) {
						r = 0 | (Math.random() * 16);
						uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
					}
				}
			}
			return uuid.join('');
		}
	}
};
</script>

<style lang="scss" scoped>
@import 'uview-ui/index.scss';
.nas-transfer {
	background: #fff;
	height: 100%;
	/deep/ .u-subsection {
		height: 96rpx !important;
		border-radius: 48rpx !important;
		margin: 0rpx 32rpx;
	}
	/deep/ .u-item-bg {
		height: 72rpx !important;
		border-radius: 36rpx !important;
		bottom: 12rpx !important;
	}
	.nas-transfer-status {
		margin: 28rpx 32rpx;
		display: flex;
		align-items: center;
		height: 56rpx;
		justify-content: space-between;
	}
	.nas-transfer-status-left {
		display: flex;
		align-items: center;
	}
	.nas-transfer-left-item {
		&:first-of-type {
			font-family: HarmonyOS_Sans_SC;
			font-size: 24rpx;
			color: #808080;
			letter-spacing: 0;
			text-align: center;
			font-weight: 400;
		}
		&:last-of-type {
			width: 339rpx;
			height: 56rpx;
			margin-left: 16rpx;
			background: rgba(219, 153, 40, 0.08);
			border-radius: 30rpx;
			display: flex;
			justify-content: space-around;
			align-items: center;
			font-family: HarmonyOS_Sans_SC;
			font-size: 24rpx;
			color: #d4ad6c;
			letter-spacing: 0;
			text-align: center;
			font-weight: 400;
			image {
				width: 26rpx;
				height: 32rpx;
			}
		}
	}
	.nas-transfer-status-right {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 139rpx;
		height: 56rpx;
		background: rgba(48, 105, 220, 0.1);
		border-radius: 28rpx;
		font-family: HarmonyOS_Sans_SC;
		font-size: 24rpx;
		color: #3069dc;
		letter-spacing: 0;
		text-align: center;
		font-weight: 400;
	}
	.nas-transfer-body {
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 0 32rpx;
		padding: 24rpx;
		border-bottom: 1rpx solid #e6e6e6;
		.nas-transfer-body-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			width: 100%;
		}
		.nas-transfer-body-left {
			image {
				width: 82rpx;
				height: 82rpx;
			}
		}
		.nas-transfer-body-info {
			margin-left: 16rpx;
			.nas-transfer-info {
				width: 440rpx;
				&:nth-of-type(1) {
					font-family: HarmonyOS_Sans_SC;
					font-size: 28rpx;
					color: #333333;
					letter-spacing: 0;
					font-weight: 400;
				}
				&:nth-of-type(2) {
					margin: 10rpx 0;
				}
				&:nth-of-type(3) {
					display: flex;
					justify-content: space-between;
					align-items: center;
					font-family: HarmonyOS_Sans_SC;
					font-size: 20rpx;
					color: rgba(128, 128, 128, 0.7);
					letter-spacing: 0;
					font-weight: 400;
				}
			}
		}
		.nas-transfer-body-right {
			width: 56rpx;
			height: 56rpx;
			margin-left: auto;
			image {
				width: 56rpx;
				height: 56rpx;
			}
		}
	}
}
</style>
